package org.wannatrak.android.executions;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.helper.DateHelper;
import org.wannatrak.android.helper.WannatrakHelper;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-15 13:14:36 +0000 (Wed, 15 Jun 2011) $ 11:50:47 AM
 * @version: $Revision: 5 $
 * @id: $Id: ProjectService.java 5 2011-06-15 13:14:36Z maxtulupov@gmail.com $
 */
public class ProjectService extends Service {

    private final int DEFAULT_TIME = 5;

    private PendingIntent pendingIntent;

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationContext.init(this);
        initSchedule();
    }

    @Override
    public void onDestroy() {
        Log.d(getClass().getSimpleName(), "destroy service");
        super.onDestroy();
        if (pendingIntent != null) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            pendingIntent = null;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    private void initSchedule() {
        Log.e(getClass().getSimpleName(), " start init service");
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(ProjectService.this, ProjectBroadcastReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(
                ProjectService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long period = calculatePeriod();
        Log.e(getClass().getSimpleName(), "period = " + period);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                DateHelper.getCurrentDateTime().getTime(),
                period,
                pendingIntent);
        Log.e(getClass().getSimpleName(), " launch pending intent");
    }

    private long calculatePeriod() {
        String trackInterval = ApplicationContext.getSettingService().loadSetting("trackInterval");
        long l = WannatrakHelper.convertStringIntervalInMillis(trackInterval);
        if (l > 0) {
            return l;
        }
        return DEFAULT_TIME * 60 * 1000L;
    }
}
